package com.hybrid.jsbridge;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * 在此写用途
 *
 * @author: zhiwei
 * @date: 2017-10-09 22:26
 * @version: 9.1.0
 */
public class WVResult {
    private int success = 0;

    public static final String SUCCESS = "HY_SUCCESS";
    public static final String FAIL = "HY_FAILED";
    public static final String PARAM_ERR = "HY_PARAM_ERR";
    public static final String NO_METHOD = "HY_NO_HANDLER";
    public static final String NO_PERMISSION = "HY_NO_PERMISSION";
    public static final String CLOSED = "HY_CLOSED";

    public static final WVResult RET_SUCCESS = new WVResult(SUCCESS);
    public static final WVResult RET_FAIL = new WVResult(FAIL);
    public static final WVResult RET_PARAM_ERR = new WVResult(PARAM_ERR);
    public static final WVResult RET_NO_METHOD = new WVResult(NO_METHOD);
    public static final WVResult RET_NO_PERMISSION = new WVResult(NO_PERMISSION);
    public static final WVResult RET_CLOSED = new WVResult(CLOSED);

    private JSONObject result = new JSONObject();

    public WVResult() {
    }

    public WVResult(String retString) {
        this.setResult(retString);
    }

    public void setData(JSONObject data) {
        if (data != null) {
            result = data;
        }
    }

    public void addData(String key, String value) {
        if (key == null || value == null) {
            return;
        }
        try {
            result.put(key, value);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public void addData(String key, JSONObject value) {
        if (key == null || value == null) {
            return;
        }
        try {
            result.put(key, value);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public void addData(String key, JSONArray value) {
        if (key == null || value == null) {
            return;
        }
        try {
            result.put(key, value);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public void setSuccess() {
        success = 1;
    }

    public void setResult(String retString) {
        try {
            result.put("ret", retString);
            success = SUCCESS.equals(retString) ? 1 : -1;
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public String toJsonString() {
        try {
            if (success == 1) {
                result.put("ret", SUCCESS);
            } else if (success == 0) {
                result.put("ret", FAIL);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return result.toString();
    }
}
